﻿Public Class COAWizardExt
    'Public ItemMasterDT As DataTable
    'Public aPL As PLSDK.PL.Void_PL

    Public aItemMasterPL As SystemBoxSDK.PL.MESSDK.ItemMaster_PL
    Public WithEvents aGridItemMaster As GridExtPL
    Public selectedItemMasterRow As DataRow
    Public selectedItemMasterRevID As String

    Public aSpecPL As SystemBoxSDK.PL.MESSDK.ItemMasterSpecification_PL
    Public WithEvents aGridSpec As GridExtPL
    Public selectedSpecList As List(Of Guid) = New List(Of Guid)

    Public aClientSpecToSavePL As SystemBoxSDK.PL.MESSDK.ClientSpecification_PL
    Public aClientSpecPL As SystemBoxSDK.PL.MESSDK.ClientSpecification_PL
    Public WithEvents aGridClientSpec As GridExtPL

    Public aSocietyPL As SystemBoxSDK.PL.CoreSDK.Society_PL
    Public WithEvents aGridSociety As GridExtPL

    Public aDocTemplatePL As SystemBoxSDK.PL.CoreSDK.DocumentTemplate_PL
    Public WithEvents aGridDocTemplate As GridExtPL
    Public selectedDocumentTemplateRow As DataRow

    Public Overridable Sub WizardControl1_CancelClick(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles WizardControl1.CancelClick
        If MessageBox.Show("Do you want to exit ?", "", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
            Me.Close()
        End If

    End Sub

    Public Overridable Sub WizardControl1_FinishClick(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles WizardControl1.FinishClick
        Me.Close()
    End Sub

    Public Overridable Sub WizardControl1_SelectedPageChanged(sender As Object, e As DevExpress.XtraWizard.WizardPageChangedEventArgs) Handles WizardControl1.SelectedPageChanged
        Select Case e.Page.Name
            Case "SelectItemMaster"
                If aItemMasterPL Is Nothing Then

                    aItemMasterPL = New SystemBoxSDK.PL.MESSDK.ItemMaster_PL("COA_ItemMaster")

                    If AppManager.SiteAccessList IsNot Nothing Then
                        If Not String.IsNullOrWhiteSpace(aItemMasterPL.SQLWhere) Then
                            aItemMasterPL.SQLWhere += " AND "
                        End If
                        aItemMasterPL.SQLWhere = String.Format("SiteId_FK in ( '00000000-0000-0000-0000-000000000000',{0})", AppManager.SiteAccessList)
                    End If



                    aGridItemMaster = New GridExtPL() With {.Dock = DockStyle.Fill, .Pl = aItemMasterPL, .LoadWithChilds = False}
                    aGridItemMaster.Name = "GridLatestItemMaster"
                    aGridItemMaster.AllowCreate = False
                    aGridItemMaster.AllowDelete = False
                    aGridItemMaster.AllowUpdate = False
                    aGridItemMaster.SetListlike()

                    e.Page.Controls.Add(aGridItemMaster)

                    AddHandler aGridItemMaster.MasterRowClick, AddressOf ItemMasterRowClick

                    If aGridItemMaster.Dataset.Tables(0).Rows.Count > 0 Then

                    End If

                End If

            Case "SelectSpec"
                If selectedItemMasterRow IsNot Nothing AndAlso selectedItemMasterRow("ItemMasterRevID").ToString() <> selectedItemMasterRevID Then
                    'ClearSummary()

                    selectedItemMasterRevID = selectedItemMasterRow("ItemMasterRevID").ToString()
                    'If aSpecPL IsNot Nothing Then
                    '    aSpecPL.Dispose()
                    'End If

                    aSpecPL = New SystemBoxSDK.PL.MESSDK.ItemMasterSpecification_PL("COA_ItemMasterSpecification_New")
                    aSpecPL.SQLWhere = String.Format("ItemMasterRevID = '{0}'", selectedItemMasterRevID)
                    aGridSpec = New GridExtPL() With {.Dock = DockStyle.Fill, .Pl = aSpecPL, .LoadWithChilds = False, .SecureGrid = False}
                    aGridSpec.Name = "GridItemMasterSpec"
                    aGridSpec.AllowCreate = False
                    aGridSpec.AllowDelete = False


                    AddHandler aGridSpec.MasterCellValueChanged, AddressOf Spec_CellValueChanged

                    e.Page.Controls.Remove(e.Page.Controls("GridItemMasterSpec"))

                    e.Page.Controls.Add(aGridSpec)
                End If

            Case "ClientSpecPage"
                If aClientSpecPL Is Nothing OrElse (selectedItemMasterRow IsNot Nothing AndAlso selectedItemMasterRow("ItemMasterRevID").ToString() <> selectedItemMasterRevID) Then

                    'If aClientSpecPL IsNot Nothing Then
                    '    aClientSpecPL.Dispose()
                    'End If

                    Dim aGuid As Guid
                    Dim strListOfGuid As String = String.Empty
                    For Each aGuid In selectedSpecList
                        strListOfGuid = strListOfGuid + "'" + aGuid.ToString() + "',"
                    Next
                    strListOfGuid = strListOfGuid.Remove(strListOfGuid.Length - 1)

                    'OUTSTANDINGISSUE: on devrait aussi filtrer pour enlever les clients qui ont deja un COA pour le ItemMasterRev choisi. clieng 2013-02-19
                    aClientSpecPL = New SystemBoxSDK.PL.MESSDK.ClientSpecification_PL("COA_ClientSpecification_New")
                    aClientSpecPL.SQLWhere = String.Format("ItemMasterRevID = '{0}' AND ItemMasterSpecRevDetailID in ({1})", selectedItemMasterRevID, strListOfGuid)
                    aGridClientSpec = Nothing
                    aGridClientSpec = New GridExtPL() With {.Dock = DockStyle.Fill, .Pl = aClientSpecPL, .LoadWithChilds = True, .SecureGrid = False}
                    aGridClientSpec.Name = "GridClientSpec"
                    aGridClientSpec.AllowCreate = False
                    aGridClientSpec.AllowDelete = False


                    'AddHandler aGridSpec.MasterCellValueChanged, AddressOf Spec_CellValueChanged

                    'e.Page.Controls.Remove(e.Page.Controls("GridClientSpec"))
                    e.Page.Controls.Add(aGridClientSpec)
                End If

            Case "SelectClient"
                If aSocietyPL Is Nothing Then
                    aSocietyPL = New SystemBoxSDK.PL.CoreSDK.Society_PL("COA_Society")
                    'aSpecPL.SQLWhere = String.Format("ItemMasterRevID = '{0}'", selectedItemMasterID)
                    aGridSociety = New GridExtPL() With {.Dock = DockStyle.Fill, .Pl = aSocietyPL, .LoadWithChilds = False, .SecureGrid = False}
                    aGridSpec.Name = "GridSociety"
                    aGridSociety.AllowCreate = False
                    aGridSociety.AllowDelete = False

                    e.Page.Controls.Add(aGridSociety)
                End If

            Case "TemplatePage"
                If aDocTemplatePL Is Nothing Then
                    aDocTemplatePL = New SystemBoxSDK.PL.CoreSDK.DocumentTemplate_PL("COA_DocumentTempalte")
                    aSpecPL.SQLWhere = String.Format("ClassId_FK = '{0}'", "31FCE47D-2F1D-438E-94F4-DCD61AE177D7") 'OUSTANDINGISSUE: mettre le Guid dans IDRepository quand on aura conclu que c'est par le ClassID_FK qu<on filtre pour avoir seulement les COA Template. clieng 2014-02-07.
                    aGridDocTemplate = New GridExtPL() With {.Dock = DockStyle.Fill, .Pl = aDocTemplatePL, .LoadWithChilds = False, .SecureGrid = False}
                    aGridDocTemplate.Name = "GridDocumentTemplate"
                    aGridDocTemplate.AllowCreate = False
                    aGridDocTemplate.AllowDelete = False

                    AddHandler aGridDocTemplate.MasterRowClick, AddressOf aGridDocTemplateRowClick

                    Dim action As ActionOption
                    action = New ActionOption("CustomOption", "ACT_000", "Preview Template", AddressOf COATemplate_ShowInDesigner, True, True)
                    aGridDocTemplate.GridActionOptionList.Add(action)

                    e.Page.Controls.Add(aGridDocTemplate)
                End If

            Case "ProgressPage"
                SaveData()


        End Select
    End Sub

    Public Overridable Sub WizardControl1_SelectedPageChanging(sender As System.Object, e As DevExpress.XtraWizard.WizardPageChangingEventArgs) Handles WizardControl1.SelectedPageChanging

        Select Case e.Page.Name
            Case "SelectItemMaster"
                lblMessage.Text = ""
            Case "SelectSpec"
                'Valider, qu'a la derniere etape, qu'un Item Master a été sélectionné sinon e.Cancel
                If selectedItemMasterRow Is Nothing Then
                    e.Cancel = True
                    lblMessage.Text = "You must select a product."
                Else
                    lblMessage.Text = ""
                End If

            Case "ClientSpecPage"
                'Valider, qu'a la derniere etape, au moins une Spec a été sélectionné sinon e.Cancel
                If selectedSpecList.Count <= 0 Then
                    e.Cancel = True
                    lblMessage.Text = "You must select at least one specification."
                Else
                    lblMessage.Text = ""
                End If

            Case "SelectClient"
                lblMessage.Text = ""

            Case "TemplatePage"
                'Valider, qu'a la derniere etape, au moins une Society a été sélectionné sinon e.Cancel
                lblMessage.Text = ""

        End Select


    End Sub


    Public Overridable Sub SaveData()
        Dim aSocietyRow As DataRow
        Dim aClientSpecRow As DataRow
        Dim itemMasterRevID As Guid = Nothing
        Dim aList As Dictionary(Of Guid, Guid) = New Dictionary(Of Guid, Guid)
        'Dim _aMetaDataTableChild As DataTable = (From aD In _aMetaDataTable.AsEnumerable() Where aD.Field(Of Integer)("LevelH") = i Select aD).CopyToDataTable

        Dim aMetaDataTable As MetaDataTable = New MetaDataTable()
        aMetaDataTable.FillBusinessApplicationData("COA_ClientSpecification_New")

        'Set MetaDatable to save
        For Each aSocietyRow In aGridSociety.MetaDataTable.Rows
            If CBool(aSocietyRow("Selected").ToString()) Then

                'Ici on ajoute les ClientSpecification
                For Each aClientSpecRow In aGridClientSpec.MetaDataTable.Rows
                    aClientSpecRow("ClientSpecificationId") = Guid.NewGuid
                    aClientSpecRow("SocietyId_FK") = CType(aSocietyRow("SocietyId"), Guid)
                    aMetaDataTable.ImportRow(aClientSpecRow)

                    itemMasterRevID = CType(aClientSpecRow("ItemMasterRevisionId_FK"), Guid)
                Next

                If Not itemMasterRevID = Nothing Then
                    aList.Add(CType(aSocietyRow("SocietyId"), Guid), itemMasterRevID)
                End If
                
            End If


        Next
        aMetaDataTable.ApplyChanges(False, aMetaDataTable, False)


        'Ici on genere la MetaQuery pour chacunes des Society
        For Each item In aList

            'GetTemplate
            Dim aRow As DataRow = Society_PL.GetSocietyByID(item.Key)
            Dim societyCD As String = aRow("SocietyCd")

            Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing

            Try
                sqlcmd = MetaQuery.GetSPCmdByMetaName("COA_GenerateMetaQuery")

                sqlcmd.Parameters("@SocietyID").Value = item.Key 'CType(aSocietyRow("SocietyId"), Guid)
                sqlcmd.Parameters("@ItemMasterRevID").Value = item.Value 'itemMasterRevID

                If Not selectedDocumentTemplateRow Is Nothing Then
                    sqlcmd.Parameters("@BinaryData").Value = GetTemplate(societyCD, selectedItemMasterRow("PrdCd"), selectedItemMasterRow("LatestRev"))
                Else
                    sqlcmd.Parameters("@BinaryData").Value = DBNull.Value
                End If


                sqlcmd.ExecuteReader(CommandBehavior.CloseConnection)
            Catch sqlex As System.Data.SqlClient.SqlException
                MessageWindow.ShowMessage(sqlex)
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Connection.Close()
                    sqlcmd.Dispose()
                End If
            End Try
        Next


        

        progressBar.Properties.Minimum = 0
        progressBar.Properties.Maximum = 100
        progressBar.Properties.Step = 10
        progressBar.Properties.ShowTitle = True
        progressBar.Properties.PercentView = True
        progressBar.Properties.Appearance.ForeColor = Color.White
        progressBar.Position = progressBar.Properties.Minimum
        RunVariableIncrement()
    End Sub

    Public Overridable Sub RunVariableIncrement()
        progressBar.Position = progressBar.Properties.Minimum
        'progressBarSample2.Position = progressBarSample2.Properties.Minimum;

        Dim currentStep As Double = (progressBar.Properties.Maximum - progressBar.Properties.Minimum) / 4
        'double currentStep = (progressBarSample2.Properties.Maximum - progressBarSample2.Properties.Minimum) / 4;

        While progressBar.Position + currentStep < progressBar.Properties.Maximum
            progressBar.Increment(CInt(Math.Ceiling(currentStep)))
            progressBar.Update()
            System.Threading.Thread.Sleep(100)
            currentStep /= 1.5

        End While

        'while(progressBarSample2.Position + currentStep < progressBarSample2.Properties.Maximum) {
        '     progressBarSample2.Increment((int)Math.Ceiling(currentStep));
        '     progressBarSample2.Update();
        '     textEditCurrentValue.Update();
        '     System.Threading.Thread.Sleep(100);
        '     currentStep /= 1.5;
    End Sub

    Public Overridable Sub COATemplate_ShowInDesigner(ByVal sender As System.Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor

        Const frmName As String = "COA Builder"

        Dim view As GridView = CType(aGridDocTemplate.GridControl1.FocusedView, GridView)
        Dim aRow As DataRow = view.GetFocusedDataRow()

        Dim newForm As ReportBuilder = New ReportBuilder With {.Name = frmName, .Text = frmName, .ShowIcon = True}
        Dim aMyXtraReport As MyXtraReport = New MyXtraReport()

        aMyXtraReport.DocumentTemplateID = Guid.Parse(aRow("DocumentTemplateId").ToString)
        aMyXtraReport.DocumentTemplateName = aRow("Name").ToString
        aMyXtraReport.QueryID_FK = Guid.Parse(aRow("QueryID_FK").ToString)
        newForm.aMyXtraReport = aMyXtraReport

        newForm.ChooseCommandEnable = False
        newForm.ChooseReportEnable = False
        newForm.NewReportEnable = False

        newForm.Show()

        Me.Cursor = Cursors.Default
    End Sub

    ''' <summary>
    ''' This sub save the selected ItemMaster everytime it changes so it can be use to filter ItemMaster's Specs in the next step
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Public Overridable Sub ItemMasterRowClick(ByVal sender As Object, ByVal e As RowClickEventArgs)
        Dim view As GridView = CType(sender, GridView)
        selectedItemMasterRow = view.GetFocusedDataRow()
    End Sub

    ''' <summary>
    ''' This sub preserve the selected DocumentTemplate everytime it changes
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub aGridDocTemplateRowClick(sender As Object, e As RowClickEventArgs)
        Dim view As GridView = CType(sender, GridView)
        selectedDocumentTemplateRow = view.GetFocusedDataRow()
    End Sub

    ''' <summary>
    ''' This sub add/remove from a list, witch will be used to save the desired test
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Public Overridable Sub Spec_CellValueChanged(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs)
        Dim view As GridView = CType(sender, GridView)
        Dim aRow As DataRow = view.GetFocusedDataRow()
        Dim aGuid As Guid = DirectCast(aRow("ItemMasterSpecRevDetailID"), Guid)

        If e.Column.FieldName = "Selected" Then
            If CBool(e.Value.ToString()) = True Then
                If selectedSpecList.Contains(aGuid) = False Then
                    selectedSpecList.Add(aGuid)
                End If
            ElseIf CBool(e.Value.ToString()) = False Then
                If selectedSpecList.Contains(DirectCast(aRow("ItemMasterSpecRevDetailID"), Guid)) = True Then
                    selectedSpecList.Remove(aGuid)
                End If
            End If
        End If
    End Sub

    Private Function GetTemplate(ByVal societyCD As String, ByVal prdCD As String, ByVal prdRevision As Integer) As Byte()
        Dim dataFormat As Guid
        Dim binaryString() As Byte
        Dim template() As Byte = Nothing

        Using mqReport As MetaQuery = MetaQuery.GetMetaQueryByName("ReadReportFromDocTemplate")
            mqReport.SQLWhere = String.Format("Name = '{0}' ", "COA_Template")
            mqReport.FillResultQuery()
            '
            If mqReport.ResultQuery.Rows.Count = 1 Then
                Dim reportString As String = mqReport.ResultQuery.Rows(0).Item("Data").ToString

                If mqReport.ResultQuery.Rows(0).Item("BinaryData") IsNot DBNull.Value Then
                    binaryString = CType(mqReport.ResultQuery.Rows(0).Item("BinaryData"), Byte())
                    dataFormat = DirectCast(mqReport.ResultQuery.Rows(0).Item("DataFormatId_FK"), Guid)

                    If Not dataFormat = Nothing AndAlso dataFormat = IdRepository.APP_DATAFORMAT_UTF8 Then

                        template = LoadDocument_UsingUTF8(binaryString, societyCD, prdCD, prdRevision)


                    End If


                End If
            End If
        End Using
        Return template
    End Function

    Private Function LoadDocument_UsingUTF8(ByVal binaryString() As Byte, ByVal societyCD As String, ByVal prdCD As String, ByVal prdRevision As Integer) As Byte()
        Dim reportString As String
        Dim report As XtraReport = Nothing
        Dim data() As Byte
        Dim encoder As UTF8Encoding

        Try
            Using msXmlReportLayout As IO.MemoryStream = New IO.MemoryStream()
                encoder = New UTF8Encoding()
                '
                reportString = Encoding.UTF8.GetString(binaryString)

                Dim COAName = "COA_" + societyCD + "_" + prdCD + "_Rev" + prdRevision.ToString
                COAName = COAName.Replace("-", "_")

                'reportName = selectedItemMasterRow("PrdCd") + 
                reportString = reportString.Replace("COA_Template", COAName)
                reportString = reportString.Replace("COATemplateQuery", COAName)

                data = encoder.GetBytes(reportString)
            End Using

        Catch ex As Exception
            Throw ex
        End Try

        Return data
    End Function

End Class